package com.tian.framework.web.exception;

import com.tian.common.core.domain.AjaxResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 *
 * @author zcx
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LogManager.getLogger(GlobalExceptionHandler.class);

    /**
     * 请求方式不支持
     */
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public String handleException(HttpRequestMethodNotSupportedException e) {
        AjaxResult ajaxResult = new AjaxResult();
        log.error(e.getMessage(), e);
        return ajaxResult.error("不支持' " + e.getMethod() + "'请求");
    }

    /**
     * 权限不足异常，（仅仅权限不足异常的全局异常的Exception优先级高于security自定义的权限不足异常，会
     * 使自定义权限不足异常无效）
     */
    @ExceptionHandler({AccessDeniedException.class,})
    public String handleException(AccessDeniedException e) {
        AjaxResult ajaxResult = new AjaxResult();
        return ajaxResult.warn("权限不足");
    }
    /**
     * 系统异常(如果不是其他则执行此默认)
     */
    @ExceptionHandler(Exception.class)
    public String handleException(Exception e) {
        AjaxResult ajaxResult = new AjaxResult();
        log.error(e.getMessage(), e);
        return ajaxResult.error("服务器错误，请联系管理员");
    }
}
